package com.zdkj.subway.st.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.entity.*;
import com.zdkj.subway.st.mapper.SwParamLineMapper;
import com.zdkj.subway.st.mapper.SwParamStationMapper;
import com.zdkj.subway.st.mapper.SwTkOfficialTicketMapper;
import com.zdkj.subway.st.service.SwTkBlackService;
import com.zdkj.subway.st.service.SwTkOfficialTicketHistoryService;
import com.zdkj.subway.st.service.SwTkOfficialTicketService;
import com.zdkj.subway.st.util.DateUtilsSt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 公务票信息管理
 *
 * @author chenbo
 * @date 2020-06-10 10:21:03
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swtkofficialticket")
@Api(value = "swtkofficialticket", tags = "公务票信息管理管理")
public class SwTkOfficialTicketController {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SwTkOfficialTicket.class);
    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    /**
     * 申办新卡 值
     */
    private static final String HANDLE_TYPE_APPLY = "0";
    /**
     * 修改 值
     */
    private static final String HANDLE_TYPE_EDIT = "1";
    /**
     * 续期 值
     */
    private static final String HANDLE_TYPE_XQ = "2";
    /**
     * 退卡 值
     */
    private static final String HANDLE_TYPE_tk = "3";
    /**
     * 遗失补办 值
     */
    private static final String HANDLE_TYPE_YSBB = "4";
    /**
     * 消磁补办 值
     */
    private static final String HANDLE_TYPE_XCBB = "5";
    /**
     * 人为损坏补办 值
     */
    private static final String HANDLE_TYPE_RWSHBB = "6";

    /**
     * 黑名单审批状态 值
     */
    private static final String STATUS_NO = "0";

    /**
     * 黑名单拉黑状态 值
     */
    private static final String BLACK_NO = "0";

    private final SwTkOfficialTicketService swTkOfficialTicketService;
    private final SwTkOfficialTicketHistoryService swTkOfficialTicketHistoryService;
    private final SwTkBlackService swTkBlackService;

    private final SwTkOfficialTicketMapper swTkOfficialTicketMapper;
    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param swTkOfficialTicket 公务票信息管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwTkOfficialTicketPage(Page page, SwTkOfficialTicket swTkOfficialTicket) {
        String nameLike = null;
        String cardNumLike = null;
        String oldCardNumLike = null;
        String idCardLike = null;
        //票卡状态 1：已过期 2：正常  虚拟标识
        String ticketStatus = swTkOfficialTicket.getTicketStatus();

        if (swTkOfficialTicket.getName() != null) {
            nameLike = swTkOfficialTicket.getName();
            swTkOfficialTicket.setName(null);
        }
        if (swTkOfficialTicket.getCardNum() != null) {
            cardNumLike = swTkOfficialTicket.getCardNum();
            swTkOfficialTicket.setCardNum(null);
        }
        if (swTkOfficialTicket.getCardNum() != null) {
            oldCardNumLike = swTkOfficialTicket.getOldCardNum();
            swTkOfficialTicket.setOldCardNum(null);
        }
        if (swTkOfficialTicket.getIdCard() != null) {
            idCardLike = swTkOfficialTicket.getIdCard();
            swTkOfficialTicket.setIdCard(null);
        }
        if (swTkOfficialTicket.getTicketStatus() != null) {
            swTkOfficialTicket.setTicketStatus(null);
        }
        LambdaQueryWrapper<SwTkOfficialTicket> queryWrapper = Wrappers.query(swTkOfficialTicket).orderByDesc("send_card_time").lambda();
        List<String> dateConditionfk = swTkOfficialTicket.getDates1();
        if (ObjectUtil.isNotEmpty(dateConditionfk)) {
            queryWrapper.between(SwTkOfficialTicket::getSendCardTime, dateConditionfk.get(0), dateConditionfk.get(1));
        }
        if(swTkOfficialTicket.getEndTimeDTO()!= null){
            queryWrapper.likeRight(SwTkOfficialTicket::getEndTime,swTkOfficialTicket.getEndTimeDTO());
        }
        //用来区分票卡状态 1：已过期 2：正常
        //判断时间 如果当前时间>=票卡结束时间 代表已过期 否则代表正常
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        if("1".equals(ticketStatus)){
            queryWrapper.lt(SwTkOfficialTicket::getEndTime,now);
        }
        if("2".equals(ticketStatus)){
            queryWrapper.ge(SwTkOfficialTicket::getEndTime,now);
        }
        return R.ok(swTkOfficialTicketService.page(page, queryWrapper
                .like(nameLike == null ? false : true, SwTkOfficialTicket::getName, nameLike)
                .like(cardNumLike == null ? false : true, SwTkOfficialTicket::getCardNum, cardNumLike)
                .like(StringUtils.isNotEmpty(swTkOfficialTicket.getUnderCenter()), SwTkOfficialTicket::getUnderCenter, swTkOfficialTicket.getUnderCenter())
                .like(StringUtils.isNotEmpty(idCardLike), SwTkOfficialTicket::getIdCard, idCardLike)
                .like(StringUtils.isNotEmpty(oldCardNumLike), SwTkOfficialTicket::getOldCardNum, oldCardNumLike)
                .eq(StringUtils.isNotEmpty(swTkOfficialTicket.getBackStatus()), SwTkOfficialTicket::getBackStatus,swTkOfficialTicket.getBackStatus())));
    }


    /**
     * 通过id查询公务票信息管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swTkOfficialTicketService.getById(id));
    }

    /**
     * 新增公务票信息管理
     *
     * @param swTkOfficialTicket 公务票信息管理
     * @return R
     */
    @ApiOperation(value = "新增公务票信息管理", notes = "新增公务票信息管理")
    @SysLog("新增公务票信息管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_add')")
    public R save(@RequestBody SwTkOfficialTicket swTkOfficialTicket) {
        //办卡类型为3 代表已退卡
        if("3".equals(swTkOfficialTicket.getHandleType())){
            LambdaQueryWrapper<SwTkOfficialTicket> tkQuery = Wrappers.<SwTkOfficialTicket>lambdaQuery()
                    .eq(SwTkOfficialTicket::getCardNum, swTkOfficialTicket.getCardNum());
            List<SwTkOfficialTicket> tkList = swTkOfficialTicketService.list(tkQuery);

            LambdaQueryWrapper<SwTkOfficialTicketHistory> tkHistoryQuery = Wrappers.<SwTkOfficialTicketHistory>lambdaQuery()
                    .eq(SwTkOfficialTicketHistory::getCardNum, swTkOfficialTicket.getCardNum());
            List<SwTkOfficialTicketHistory> tkHistoryList = swTkOfficialTicketHistoryService.list(tkHistoryQuery);
            //退卡状态为已退卡的 修改其他办卡类型的退卡状态为已退卡
            if (CollectionUtil.isNotEmpty(tkList)){
                tkList.forEach(x -> x.setBackStatus("2"));
                swTkOfficialTicketService.updateBatchById(tkList);
            }
            if (CollectionUtil.isNotEmpty(tkHistoryList)){
                tkHistoryList.forEach(x -> x.setBackStatus("2"));
                swTkOfficialTicketHistoryService.updateBatchById(tkHistoryList);
            }
            swTkOfficialTicket.setBackStatus("2");
        }else {
            swTkOfficialTicket.setBackStatus("1");
        }
        /**
         * 每一个身份证号只能有一条记录
         */
        //SwTkOfficialTicket selByIdCard = new SwTkOfficialTicket();
        //selByIdCard.setIdCard(swTkOfficialTicket.getIdCard());
//        SwTkOfficialTicket one = swTkOfficialTicketService.getOne(Wrappers.query(selByIdCard).last("LIMIT 1"));
//        if (one != null) {
//            return R.failed("该身份证号已存在记录，请核对");
//        } else {
            /**
             * 保留传进来的
             */
            SwTkOfficialTicket sourceBean = new SwTkOfficialTicket();
            BeanUtil.copyProperties(swTkOfficialTicket, sourceBean);
            /**
             * 保存公务票信息
             */
            SwTkOfficialTicket defaultObj = ObjectUtils.getDefaultObj(SwTkOfficialTicket.class);
            BeanUtil.copyProperties(swTkOfficialTicket, defaultObj, ObjectUtils.getNullAndEmptyPropertyNames(sourceBean));
            swTkOfficialTicketService.save(defaultObj);
            /**
             * 保存公务票办理历史信息
             */
            SwTkOfficialTicketHistory swTkOfficialTicketHistory = ObjectUtils.getDefaultObj(SwTkOfficialTicketHistory.class);
            swTkOfficialTicketHistory.setRelationId(defaultObj.getId());
            BeanUtil.copyProperties(sourceBean, swTkOfficialTicketHistory);

            saveBlack(defaultObj);

            return R.ok(swTkOfficialTicketHistoryService.save(swTkOfficialTicketHistory));
        //}
    }

    private void saveBlack(SwTkOfficialTicket defaultObj) {
        /**
         * 如果类型为 遗失补办将记录插入黑名单
         */
        if(StringUtils.isEmpty(defaultObj.getHandleType())){
            return ;
        }

        if (defaultObj.getHandleType().equals(HANDLE_TYPE_YSBB)) {
            SwTkBlack swTkBlack = new SwTkBlack();
            swTkBlack.setRelationId(defaultObj.getId());
            swTkBlack.setCardNum(defaultObj.getCardNum());
            swTkBlack.setName(defaultObj.getName());
            swTkBlack.setBelongUnit(defaultObj.getBelongUnit());
            swTkBlack.setBlackStatus(BLACK_NO);
            swTkBlack.setHandleStatus(STATUS_NO);
            swTkBlack.setTicketType(defaultObj.getOfficialType());
            swTkBlack.setSubmitTime(LocalDateTime.now());
            swTkBlack.setCreatorId(SecurityUtils.getUser().getId());
            swTkBlack.setDeptId(SecurityUtils.getUser().getDeptId());
            swTkBlackService.save(swTkBlack);
        }
    }

    /**
     * 修改公务票信息管理
     *
     * @param swTkOfficialTicket 公务票信息管理
     * @return R
     */
    @ApiOperation(value = "修改公务票信息管理", notes = "修改公务票信息管理")
    @SysLog("修改公务票信息管理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_edit')")
    public R updateById(@RequestBody SwTkOfficialTicket swTkOfficialTicket) {

        /**
         *先删除黑名单原有记录
         */
        LambdaQueryWrapper<SwTkBlack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SwTkBlack::getRelationId,swTkOfficialTicket.getId());
        swTkBlackService.remove(wrapper);
        /**
         * 如果类型为 遗失补办、消磁补办、人为损坏补办将记录插入黑名单
         */
        saveBlack(swTkOfficialTicket);
        /**
         *先删除公务票原有记录
         */
        LambdaQueryWrapper<SwTkOfficialTicketHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SwTkOfficialTicketHistory::getRelationId,swTkOfficialTicket.getId());
        swTkOfficialTicketHistoryService.remove(queryWrapper);
        /**
         * 去除不需要个性化字段复制属性
         */
        SwTkOfficialTicketHistory swTkOfficialTicketHistory = new SwTkOfficialTicketHistory();
        BeanUtil.copyProperties(swTkOfficialTicket, swTkOfficialTicketHistory, new String[]{
                "id", "updateTime", "delFlag"
        });
        swTkOfficialTicketHistory.setRelationId(swTkOfficialTicket.getId());
        swTkOfficialTicketHistory.setCreateTime(LocalDateTime.now());
        swTkOfficialTicketHistory.setDeptId(SecurityUtils.getUser().getDeptId());
        swTkOfficialTicketHistory.setCreatorName(SecurityUtils.getUser().getNikeName());
        swTkOfficialTicketHistory.setCreatorId(SecurityUtils.getUser().getId());
        //办卡类型为3 代表已退卡
        if("3".equals(swTkOfficialTicket.getHandleType())){
            LambdaQueryWrapper<SwTkOfficialTicket> tkQuery = Wrappers.<SwTkOfficialTicket>lambdaQuery()
                    .eq(SwTkOfficialTicket::getCardNum, swTkOfficialTicket.getCardNum());
            List<SwTkOfficialTicket> tkList = swTkOfficialTicketService.list(tkQuery);

            LambdaQueryWrapper<SwTkOfficialTicketHistory> tkHistoryQuery = Wrappers.<SwTkOfficialTicketHistory>lambdaQuery()
                    .eq(SwTkOfficialTicketHistory::getCardNum, swTkOfficialTicket.getCardNum());
            List<SwTkOfficialTicketHistory> tkHistoryList = swTkOfficialTicketHistoryService.list(tkHistoryQuery);
            //退卡状态为已退卡的 修改其他办卡类型的退卡状态为已退卡
            if (CollectionUtil.isNotEmpty(tkList)){
                tkList.forEach(x -> x.setBackStatus("2"));
                swTkOfficialTicketService.updateBatchById(tkList);
            }
            if (CollectionUtil.isNotEmpty(tkHistoryList)){
                tkHistoryList.forEach(x -> x.setBackStatus("2"));
                swTkOfficialTicketHistoryService.updateBatchById(tkHistoryList);
            }
            swTkOfficialTicket.setBackStatus("2");
            swTkOfficialTicketHistory.setBackStatus("2");
        }else {
            swTkOfficialTicket.setBackStatus("1");
            swTkOfficialTicketHistory.setBackStatus("1");
        }
        /**
         * 修改公务票信息
         */
        swTkOfficialTicketService.updateById(swTkOfficialTicket);
        /**
         * 向历史表插入数据
         */
        return R.ok(swTkOfficialTicketHistoryService.save(swTkOfficialTicketHistory));
    }


//    /**
//     * 导出
//     *
//     * @param page               分页对象
//     * @param swTkOfficialTicket 公务票信息
//     * @return
//     */
//    @ApiOperation(value = "公务票信息导出", notes = "公务票信息导出")
//    @GetMapping("/export")
//    //TODO 待确定状态字段
//    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_export')")
//    public void getSwStInvoiceBalanceExport(Page page, SwTkOfficialTicket swTkOfficialTicket, HttpServletResponse response) throws IOException {
//        Page a = swTkOfficialTicketService.pageExport(page, new CustomQueryWrapper(SwTkOfficialTicket.class)
//                .addDTO(swTkOfficialTicket)
//                .addAlis("a")
//                .addDelFlag(Boolean.TRUE)
//                .init());
//        // 写法1
//        String fileName = URLEncoder.encode("公务票信息", "UTF-8");
//        //"C:\\Users\\Administrator\\Desktop\\" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
//        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//        // 如果这里想使用03 则 传入excelType参数即可
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + DateUtilsSt.getDatetimeNowFormatter() + ".xlsx");
//        EasyExcel.write(response.getOutputStream(), SwTkOfficialTicket.class).registerConverter(new LocalDateTimeConverter())
//                .registerConverter(new LocalDateConverter()).sheet("公务票信息").doWrite(a.getRecords());
//    }


    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "导出", notes = "导出")
    @GetMapping({"/export"})
    @SysLog("公务票信息导出")
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_export')")
    public void export(SwTkOfficialTicket swTkOfficialTicket, HttpServletResponse response) {
        swTkOfficialTicketService.export(swTkOfficialTicket,response);

    }
    @ApiOperation(value = "批量导入公务票信息", notes = "批量导入公务票信息")
    @SysLog("批量导入公务票信息")
    @PostMapping("/saveBatch")
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_import')")
    @Transactional(rollbackFor = Exception.class)
    public R saveBatch(@RequestParam("file") MultipartFile file) throws Exception {
        File excelFile = MultipartFileToFile.multipartFileToFile(file);
        PigxUser user = SecurityUtils.getUser();
        List<SwTkOfficialTicket> objects = new ArrayList<>();
        List<SwTkOfficialTicketHistory> objectsHistory = new ArrayList<>();
        List<SwTkOfficialTicket> updateTkList = new ArrayList<>();
        List<SwTkOfficialTicketHistory> updateTkHistoryList = new ArrayList<>();
        Map<String, String> officialTypeMaps = new HashMap<>();//公务票类型
        Map<String, String> handleTypeMaps = new HashMap<>();//办卡类型
        List<SysDictItem> officialTypeList = swTkOfficialTicketMapper.officialTypeMaps();
        for (SysDictItem sysDictItem : officialTypeList) {
            officialTypeMaps.put(sysDictItem.getLabel(),sysDictItem.getValue());
        }
        List<SysDictItem> handleTypeList = swTkOfficialTicketMapper.handleTypeMaps();
        for (SysDictItem sysDictItem : handleTypeList) {
            handleTypeMaps.put(sysDictItem.getLabel(),sysDictItem.getValue());
        }
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {

                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                //业务处理
                SwTkOfficialTicket swTkOfficialTicket = new SwTkOfficialTicket();
                SwTkOfficialTicketHistory tkOfficialTicketHistory = new SwTkOfficialTicketHistory();

                //格式进行校验
                R validation = validation(m, data, officialTypeMaps, handleTypeMaps);
                if(1 == validation.getCode()){
                    return validation;
                }
                swTkOfficialTicket.setCardNum(data.get(2));
                tkOfficialTicketHistory.setCardNum(data.get(2));

                QueryWrapper<SwTkOfficialTicket> tkQuery = Wrappers.query(swTkOfficialTicket);
                List<SwTkOfficialTicket> tkList = swTkOfficialTicketService.list(tkQuery);
                QueryWrapper<SwTkOfficialTicketHistory> tkHistoryQuery = Wrappers.query(tkOfficialTicketHistory);
                List<SwTkOfficialTicketHistory> tkHistoryList = swTkOfficialTicketHistoryService.list(tkHistoryQuery);

                swTkOfficialTicket.setOfficialType(officialTypeMaps.get(data.get(0)));
                swTkOfficialTicket.setOldCardNum(data.get(1));
                swTkOfficialTicket.setApplyNum(data.get(3));
                swTkOfficialTicket.setName(data.get(4));
                swTkOfficialTicket.setIdCard(data.get(5));
                swTkOfficialTicket.setBelongUnit(data.get(6));
                swTkOfficialTicket.setUnderCenter(data.get(7));
                swTkOfficialTicket.setHandleType(handleTypeMaps.get(data.get(8)));
                if("3".equals(handleTypeMaps.get(data.get(8)))){
                    swTkOfficialTicket.setBackStatus("2");//办卡类型为3 退卡状态为已退卡
                    if(CollectionUtil.isNotEmpty(tkList)){
                        updateTkList.addAll(tkList);
                    }
                    if(CollectionUtil.isNotEmpty(tkHistoryList)){
                        updateTkHistoryList.addAll(tkHistoryList);
                    }
                }else {
                    swTkOfficialTicket.setBackStatus("1");//退卡状态为未退卡
                }
                swTkOfficialTicket.setStartTime(DateUtilsSt.LocalDateTimeToString(data.get(9)));
                swTkOfficialTicket.setEndTime(DateUtilsSt.LocalDateTimeToString(data.get(10)));
				
				String lineName = data.get(11);
				String stationName = data.get(12);
				//添加页面增加线路和车站，选择本站卡和为必填项，临时通行卡是线路必填项。
                if(StringUtils.isNotEmpty(lineName)){
                    SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getName, data.get(11)));
                    if(ObjectUtil.isEmpty(swParamLine)){
                        return R.failed("导入失败，请检查第" + (m+3) +"行【线路】后重新导入！");
                    }
                    swTkOfficialTicket.setLineCode(swParamLine.getCode());//线路
                }else{
                    if("0".equals(swTkOfficialTicket.getOfficialType())) {//选择本站卡是线路必填项
                        return R.failed("导入失败，请检查第" + (m+3) +"行【线路】后重新导入！");
                    }
                }
                if(StringUtils.isNotEmpty(lineName)&&StringUtils.isNotEmpty(stationName)){
                    SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                            .eq(SwParamStation::getLineCode, swTkOfficialTicket.getLineCode()).eq(SwParamStation::getName, data.get(12)));
                    if(ObjectUtil.isEmpty(swParamStation)){
                        return R.failed("导入失败，请检查第" + (m+3) +"行【站点】后重新导入！");
                    }
                    swTkOfficialTicket.setStationCode(swParamStation.getCode());//站点
                }else{
                    if("0".equals(swTkOfficialTicket.getOfficialType())) {//选择本站卡是车站必填项
                        return R.failed("导入失败，请检查第" + (m+3) +"行【站点】后重新导入！");
                    }
                }
				swTkOfficialTicket.setRemark(data.get(13));
                swTkOfficialTicket.setDeptId(user.getDeptId());
                swTkOfficialTicket.setCreatorId(user.getId());
                swTkOfficialTicket.setCreatorName(user.getNikeName());
                swTkOfficialTicket.setCreateTime(LocalDateTime.now());
                objects.add(swTkOfficialTicket);
                //同步保存公务票办理历史信息
                /**
                 * 去除不需要个性化字段复制属性
                 */
                SwTkOfficialTicketHistory swTkOfficialTicketHistory = new SwTkOfficialTicketHistory();
                BeanUtil.copyProperties(swTkOfficialTicket, swTkOfficialTicketHistory, new String[]{
                        "id", "updateTime", "delFlag"
                });
                swTkOfficialTicketHistory.setRelationId(swTkOfficialTicket.getId());
                objectsHistory.add(swTkOfficialTicketHistory);

                //如果类型为 遗失补办将记录插入黑名单
                saveBlack(swTkOfficialTicket);
            }
        }
        if (CollectionUtil.isNotEmpty(objects)){
            swTkOfficialTicketService.saveBatch(objects);
        }
        if (CollectionUtil.isNotEmpty(objectsHistory)){
            swTkOfficialTicketHistoryService.saveBatch(objectsHistory);
        }
        //退卡状态为已退款的 修改其他办卡类型的退卡状态为已退款
        if (CollectionUtil.isNotEmpty(updateTkList)){
            updateTkList.forEach(x -> x.setBackStatus("2"));
            swTkOfficialTicketService.updateBatchById(updateTkList);
        }
        if (CollectionUtil.isNotEmpty(updateTkHistoryList)){
            updateTkHistoryList.forEach(x -> x.setBackStatus("2"));
            swTkOfficialTicketHistoryService.updateBatchById(updateTkHistoryList);
        }
        return R.ok();
    }
    /**
     * 格式校验
     * @param m
     * @param data
     * @param officialTypeMaps
     * @param handleTypeMaps
     * @return
     */
    public R validation(int m, Map<Integer, String> data, Map<String, String> officialTypeMaps, Map<String, String> handleTypeMaps) {
        String format = "yyyy-MM-dd HH:mm:ss";
        if(!officialTypeMaps.containsKey(data.get(0))){
            return R.failed("请检查 第" + (m+3) +"行 公务票类型是否正确！");
        }
        //if(data.get(5).length() > 18 || StrUtil.isBlank(data.get(5)) || RegExUtilOrString.getPatternStr(data.get(5))){
        //    return R.failed("请检查 第" + (m+3) +"行 身份证卡号格式是否正确！");
        //}
        if(!handleTypeMaps.containsKey(data.get(8))){
            return R.failed("请检查 第" + (m+3) +"行 办卡类型是否正确！");
        }
        boolean date2 = DateUtilsSt.isDate(data.get(9), format);//检查日期格式是否正确
        if(!date2){
            return R.failed("请检查 第" + (m+3) +"行 开始日期格式是否正确！");
        }
        boolean date3 = DateUtilsSt.isDate(data.get(10), format);//检查日期格式是否正确
        if(!date3){
            return R.failed("请检查 第" + (m+3) +"行 截止日期格式是否正确！");
        }
        return R.ok();
    }
	/*
	  导出模版
	*/
	@ApiOperation(value = "公务票信息模版下载", notes = "公务票信息模版下载")
    @GetMapping("/exportTamplateOfficial")
    public void exportTamplateOffical(HttpServletResponse response) {

		String  verifyConfirmName = "公务票信息模版";
        String  tableName = "sw_tk_official_ticket";

        BufferedInputStream br = null;
        OutputStream out = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode(verifyConfirmName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            br =  new BufferedInputStream(this.getClass().getResourceAsStream("/static/excel/template/import/" + tableName + ".xlsx"));

            byte[] buf = new byte[1024];
            int len = 0;

            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
       
    }

    /**
     * 通过ids删除公务票信息管理
     *
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过ids删除公务票信息管理", notes = "通过ids删除公务票信息管理")
    @SysLog("通过ids删除公务票信息管理")
    @DeleteMapping("/removeByIds")
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_delBatch')")
    public R removeByIds(@RequestBody List<Integer> ids) {
        if(CollectionUtil.isNotEmpty(ids)) {
            ids.forEach(item -> {
                /**
                 *同时删除黑名单记录
                 */
                LambdaQueryWrapper<SwTkBlack> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SwTkBlack::getRelationId, item);
                swTkBlackService.remove(wrapper);
                /**
                 *同时删除公务票记录
                 */
                LambdaQueryWrapper<SwTkOfficialTicketHistory> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SwTkOfficialTicketHistory::getRelationId, item);
                swTkOfficialTicketHistoryService.remove(queryWrapper);
            });
        }
        return R.ok(swTkOfficialTicketService.removeByIds(ids));
    }

    /**
     * 通过id删除公务票信息管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除公务票信息管理", notes = "通过id删除公务票信息管理")
    @SysLog("通过id删除公务票信息管理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_swtkofficialticket_del')")
    public R removeById(@PathVariable Integer id) {
        /**
         *同时删除黑名单记录
         */
        LambdaQueryWrapper<SwTkBlack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SwTkBlack::getRelationId, id);
        swTkBlackService.remove(wrapper);
        /**
         *同时删除公务票记录
         */
        LambdaQueryWrapper<SwTkOfficialTicketHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SwTkOfficialTicketHistory::getRelationId, id);
        swTkOfficialTicketHistoryService.remove(queryWrapper);
        return R.ok(swTkOfficialTicketService.removeById(id));
    }

}
